import os
import sys

from ai_translator.model import OpenAIModel
from ai_translator.translator import PDFTranslator
from ai_translator.utils import ConfigLoader, ArgumentParser

# set root_dir = os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))


class Translator:
    def __init__(self, pdf_file_path, file_format='markdown', target_language='简体中文', model_type='OpenAIModel',
                 config_path='config.yaml'):
        self.openai_mode = None
        self.pdf_file_path = pdf_file_path
        self.file_format = file_format
        self.target_language = target_language
        self.mode_type = model_type
        self.config_path = config_path
        self.init_open_ai_mode()

    def init_open_ai_mode(self):
        config_json = ConfigLoader(self.config_path).load_config()
        #  模型名字
        name = config_json['OpenAIModel']['openai_model']
        key = config_json['OpenAIModel']['api_key']
        self.openai_mode = OpenAIModel(model_name=name, api_key=key)

    def start(self):
        if self.pdf_file_path is None:
            raise 'pdf_file_path不能没有'
        if self.openai_mode is None:
            raise 'openai_mode配置不正确'
        PDFTranslator(self.openai_mode).translate_pdf(pdf_file_path=self.pdf_file_path, file_format=self.file_format,
                                                      target_language=self.target_language)


if __name__ == '__main__':
    argument_parser = ArgumentParser()

    args = argument_parser.arguments_parser()
    config_loader = ConfigLoader(args.config)
    config = config_loader.load_config()
    #  模型名字
    model_name = args.openai_model if args.openai_model else config['OpenAIModel']['openai_model']
    api_key = args.api_key if args.api_key else config['OpenAIModel']['api_key']
    # 校验模型参数是否完善
    argument_parser.check_oepnai_args(model_type=args.model_type, openai_model=model_name,
                                      api_key=api_key)

    # 文件路径
    pdf_file_path = args.book if args.book else config['common']['book']
    file_format = args.file_format if args.file_format else config['common']['file_format']

    openai_mode = OpenAIModel(model_name=model_name, api_key=api_key)

    # 开始翻译
    PDFTranslator(openai_mode).translate_pdf(pdf_file_path=pdf_file_path, file_format='markdown',
                                             target_language='繁体中文')
